package br.com.maternity.componentes.dropdownlist;

import java.lang.reflect.Method;
import java.util.List;

public class DropDownList {

    private String id;
    private String name;
    private List<Object> dataSource;
    private String dataFieldMethod;
    private String dataValueMethod;
    private int selectedIndex;
    private boolean enabled;

    public DropDownList(String _id, String _name, List<Object> _dataSource, String _dataFieldMethod, String _dataValueMethod) {
        id = _id;
        name = _name;
        dataSource = _dataSource;
        dataFieldMethod = _dataFieldMethod;
        dataValueMethod = _dataValueMethod;
        selectedIndex = -1;
        enabled = true;
    }

    public void setSelectedIndex(int value) {
        selectedIndex = value;
    }
    
    public void disable(){
        enabled = false;
    }
    
    public void enable(){
        enabled = true;
    }
    

    public String render() {
        String s = "<select name='" + name + "' id='" + id + "'";
        if(!enabled){
            s += " disabled='disabled'>";
        }else{
            s += ">";
        }
        if (selectedIndex == -1) {
            s += "<option value='-1' selected>Selecione...</option>";
        } else {
            s += "<option value='-1'>Selecione...</option>";
        }

        if (dataSource == null) {
            s += "</select>";
            return s;
        }

        int count = 0;
        try {
            for (Object obj : dataSource) {
                Method m = obj.getClass().getMethod(dataValueMethod, null);
                Object value = m.invoke(obj, new Object[]{});
                m = obj.getClass().getMethod(dataFieldMethod, null);
                Object field = m.invoke(obj, new Object[]{});

                if (count == selectedIndex) {
                    s += "<option value='" + value.toString() + "' selected>" + field.toString() + "</option>";
                } else {
                    s += "<option value='" + value.toString() + "'>" + field.toString() + "</option>";
                }
                count++;
            }
        } catch (Exception ex) {
        }
        s += "</select>";
        return s;
    }
}